<script>
	const chatSet = require('./utils/chat.js');
	// #ifdef APP-PLUS|| MP
	const permissionSet = require('@/utils/checkpermission.js');
	// #endif
	//#ifdef APP-PLUS
	var jpushModule = uni.requireNativePlugin("JG-JPush");
	// #endif
	export default {
		globalData: {
			//webscoket通讯地及端口号
			// ws_domain: 'wss://fangcan.lexiakj.com:8313',
			// ws_domain: 'wss://jiahe.dev3.lishengli.xin',
			ws_domain: '',
			//api请求接口域名
			// web_url: 'https://fangcan.lexiakj.com',
			web_url: 'https://jiahe.dev3.lishengli.xin',
			//h5访问域名配置
			h5_url: 'https://jiahe.dev3.lishengli.xin/uniapp',
			config: {
				cdn_url: '',
				//图片资源域名
				platform_contact_tel: '',
				//平台热线电话
				app_logo: '',
				//logo
				about_article: null,
				//
				agreement_article: null,
				//
				coupon_img: '',
				//
				coupon_end_time: '',
				//
				withdraw_rule: '',
				activity_rule: '1.邀请人分享专属二维码给朋友圈好友，被邀请人扫码注册上平台，即为一个邀请，被邀请人信息，可在我的页面-我的团队中显示。',
				share_image: '',
				house_trend_image: '',
				helpyou_image: '',
				complain_image: '',
				service_user_id: 0,
			},

			chat_config: {
				SocketTask: null,
				Timer: null,
				ErrorMsg: [],
				MaxRetryCount: 300, // 最大重连次数
				CurrentRetryCount: 0,
				url: '',
				ortherdata: null, //其他通用数据
				session_list: null, //聊天列表数据
				session_time: 0, //当前最小时间
				session_id: 0, //当前最小id
				session_list_callback: null, //获取列表回调数据
				search_session_list_callback: null, //获取列表回调数据
				new_session_list_callback: null, //新增列表回调数据
				msg_list_callback: null, //聊天记录回调数据
				new_msg_callback: null,
				blacklist_callback: null, //黑名单列表
				del_blacklist_callback: null,
				noticelist_callback: null,
				changenotice_callback: null,
			},
			userInfo: null,
			nowThat: null,
			nowCb: null,
			pagesParam: null,
			is_need_page_change: false,
			pagesParamImagesArr: [],
			pagesParamHouseInfo: [],
			pid: 0,
			taskData: [],
			countDownNum: 0,
			countDownTimer: null,
			getTaskData: function() {
				if (!uni.getStorageSync('token')) {
					return false;
				}
				var that = this;
				uni.request({
					url: that.web_url + '/api/xiluhouse/Score/index',
					data: {},
					header: {
						'content-type': 'application/x-www-form-urlencoded',
						TOKEN: uni.getStorageSync('token')
					},
					method: 'POST',
					dataType: 'json',
					success: function(res) {
						// console.log(res);
						if (res.data.code == 1) {
							var data = res.data.data;
							that.taskData = data.task_data;
							that.startCountDown();
						}
					},
					fail: function(res) {},
					complete: function(res) {}
				});
			},

			startCountDown() {
				var that = this;
				var taskData = that.taskData;
				var countDownNum = 0;
				var task_id = 0;
				taskData.forEach((element) => {
					if (element.type == 3 && element.limit_seconds > 0 && !element.is_complete) {
						countDownNum = element.limit_seconds;
						task_id = element.id
					}
				});
				clearInterval(that.countDownTimer);

				if (countDownNum > 0) {
					that.countDownTimer = setInterval(function() {
						//这里把setInterval赋值给变量名为timer的变量
						//每隔一秒countDownNum就减一，实现同步
						countDownNum--; //然后把countDownNum存进data，好让用户知道时间在倒计着
						that.countDownNum = countDownNum;
						uni.$emit('countDownCb', countDownNum)
						if (countDownNum == 0) {
							uni.request({
								url: that.web_url + '/api/xiluhouse/Score/dotask',
								data: {
									task_id: task_id
								},
								header: {
									'content-type': 'application/x-www-form-urlencoded',
									TOKEN: uni.getStorageSync('token')
								},
								method: 'POST',
								dataType: 'json',
								success: function(res) {}
							});
							//这里特别要注意，计时器是始终一直在走的，如果你的时间为0，那么就要关掉定时器！不然相当耗性能
							//因为timer是存在data里面的，所以在关掉时，也要在data里取出后再关闭
							clearInterval(that.countDownTimer); //关闭定时器之后，可作其他处理codes go here
						}
					}, 1000);
				}
			},

			check_setting: function(scopename, cb) {
				var that = this;
				// #ifdef MP
				var scopnameArr = ['scope.userLocation', 'scope.writePhotosAlbum', 'scope.camera'];
				if (scopnameArr.indexOf(scopename) == -1) {
					uni.showToast({
						title: '请配置好scope 列表',
						icon: 'none'
					})
				}
				var scopeArr = {
					'scope.userLocation': '地理位置',
					'scope.writePhotosAlbum': '保存到相册',
					'scope.camera': '摄像头'
				};
				uni.getSetting({
					success: function(res) {
						if (res.authSetting[scopename] == false) {
							// 拒绝授权，弹窗提示
							that.msg_setting(scopeArr[scopename]);
						} else {
							cb();
						}
					}
				});
				// #endif
			},
			//获取用户位置
			getLocation: function(cb) {
				var that = this;
				// #ifdef APP-PLUS|| MP
				permissionSet.checkPermission('location', function() {
					that.getlatlng(cb);
				})
				return false;
				// #endif

				that.getlatlng(cb);
			},
			getlatlng: function(cb) {
				//调用位置接口
				uni.getLocation({
					type: 'gcj02',
					//默认为 wgs84 返回 gps 坐标，gcj02 返回可用于wx.openLocation的坐标
					success: function(res) {
						uni.setStorageSync('latitude', res.latitude);
						uni.setStorageSync('longitude', res.longitude);

						if (typeof cb == 'function') {
							cb(res);
						}
					},
					fail(res) {
						console.log('fail:',res);
						// if (typeof cb == 'function') {
						// 	cb(res);
						// }
					}
				});
			},

			// 初始化获取基础配置信息
			init_config: function() {
				var that = this;
				uni.request({
					url: that.web_url + '/api/xiluhouse/Common/init_config',
					data: {},
					header: {
						'content-type': 'application/x-www-form-urlencoded'
					},
					method: 'POST',
					success: function(res) {
						if (res.data.code == 1) {
							that.config = res.data.data;
						}
					},
					fail: function(res) {}
				});

			},
			//获取App的更新版本
			checkUpdate: function() {
				var that = this;
				plus.runtime.getProperty(plus.runtime.appid, function(widgetInfo) {
					var version = widgetInfo.version;

					var platform = plus.os.name;
					if (plus.os.name == 'Android') {
						platform = 'android';
					} else if (plus.os.name == 'iOS') {
						platform = 'ios';
					}



					uni.request({
						url: that.web_url + '/api/xiluhouse.common/check_version',
						data: {
							version: version,
							platform: platform
						},
						header: {
							'content-type': 'application/x-www-form-urlencoded'
						},
						method: 'POST',
						success: function(res) {
							// console.log(res)
							if (res.data.code == 1) {
								if (res.data.data.newversion) {
									plus.nativeUI.confirm("检测到有新版本，是否更新", function(e) {
										if (e.index == 0) {
											if (plus.networkinfo.getCurrentType() != 3) {
												plus.nativeUI.confirm(
													"检测到您目前非Wifi连接，是否继续更新",
													function(e) {
														if (e.index == 0) {

															that.downWgt(res.data.data
																.downloadurl);
														} else {

														}
													}, "", )["取消", "确定"]
												return;
											}
											that.downWgt(res.data.data.downloadurl); //下载文件
										} else {
											//plus.runtime.quit();//安卓控制不更新退出应用

										}
									}, "", ["立即更新", "以后再说"]);

									//dtask.start();
								}

							} else {

							}
						},
						fail: function(res) {

						}
					});





				});


			},
			downWgt(url) {

				plus.nativeUI.showWaiting("正在更新，请耐心等待...");
				uni.downloadFile({ //执行下载
					url: url, //下载地址
					success: downloadResult => { //下载成功
						uni.hideLoading();
						if (downloadResult.statusCode == 200) {
							plus.runtime.install( //安装
								downloadResult.tempFilePath, {
									force: true
								},

							);
						}
					}
				});
			},
			initJpush() {
				jpushModule.initJPushService();
				this.setTags();
			},
			getUserInfo(cb){
				var that=this;
				if (uni.getStorageSync('token')) {
					var user_id=that.userInfo?that.userInfo.id:0;
					if(!user_id){
						uni.request({
							url: that.web_url + '/api/xiluhouse/User/index',
							data: {},
							sslVerify: false,
							header: {
								'content-type': 'application/x-www-form-urlencoded',
								TOKEN: uni.getStorageSync('token')
							},
							method: 'POST',
							dataType: 'json',
							success: function(res) {
								if (res.data.code === 1) {
									that.userInfo = res.data.data;
									cb(that.userInfo);
								}
							},
						});
					}else{
						cb(that.userInfo);
					}
					return false;
				}
				cb(false);
			},
			setTags() {
				var msg_on_state=uni.getStorageSync('msg_on_state')||'msg_on';
				jpushModule.addTags({
					'tags': [msg_on_state]
				})
				if (uni.getStorageSync('token')&&msg_on_state=='msg_on') {
					this.getUserInfo(function(userInfo){
						var user_id=userInfo.id;
						// 设置别名
						jpushModule.updateTags({
							'tags': [msg_on_state, '' + user_id]
						})
					})
				}
				jpushModule.addNotificationListener(result => {
					// let notificationEventType = result.notificationEventType
					// let messageID = result.messageID
					// let title = result.title
					// let content = result.content
					// let extras = result.extras
					console.log('通知事件回调', result)
				})
			},

		},
		onLaunch: function() {
			// #ifdef MP
			chatSet(this.$scope);
			this.globalData.init_config();
			if (uni.getStorageSync('token')) {
				this.globalData.chat_config.url = this.globalData.ws_domain + '?token=' + uni.getStorageSync('token');
				this.$scope.ConnectSocket();
			}
			// #endif
			//#ifndef MP
			chatSet(this);
			this.globalData.init_config();
			if (uni.getStorageSync('token')) {
				this.globalData.chat_config.url = this.globalData.ws_domain + '?token=' + uni.getStorageSync('token');
				this.ConnectSocket();
			}
			//#ifdef APP-PLUS
			this.globalData.initJpush();
			this.globalData.checkUpdate();
			// 锁定竖屏
			plus.screen.lockOrientation("portrait-primary");
			// #endif
			// #endif
		},
		onShow: function() {
			//this.globalData.getTaskData();
		},
	}
</script>

<style lang="scss">
	/*每个页面公共css */
	@import "@/uni_modules/uview-ui/index.scss";
	@import "static/css/global.css";

	.zixun-pop {
		position: relative;
		padding: 90rpx 40rpx 40rpx;
		width: 600rpx;
		max-height: 900rpx;
		background: #ffffff;
		overflow-y: scroll;
		border-radius: 8rpx;
	}

	.zixun-pop .input-box {
		width: 100%;
		height: 90rpx;
		background: #f6f7fa;
		border-radius: 10rpx;
	}

	.zixun-pop .input {
		font-size: 30rpx;
		color: #333;
		line-height: 42rpx;
	}

	.zixun-pop .btn1 {
		width: 100%;
		height: 90rpx;
		background: #0091ff;
		box-shadow: 0 4rpx 40rpx 0 rgba(3, 103, 179, 0.3);
		border-radius: 10rpx;
		font-size: 30rpx;
		color: #ffffff;
		line-height: 90rpx;
		text-align: center;
	}

	.zixun-pop .btn2 {
		width: 100%;
		height: 90rpx;
		background: #ff7b40;
		box-shadow: 0 4rpx 40rpx 0 rgba(248, 103, 56, 0.3);
		border-radius: 10rpx;
		font-size: 30rpx;
		color: #ffffff;
		line-height: 90rpx;
		text-align: center;
	}
</style>
